<template>
  <BasicModal
    :title="title"
    :width="800"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :showOkBtn="type !== 'detail'"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { tenantApplicationFormSchemas } from '../tenant.data';
  import { createTenantApplication } from '/@/api/tenant';

  const emit = defineEmits(['register', 'success']);

  const type = ref('create');
  const recordId = ref('');

  const title = computed(() => {
    switch (type.value) {
      case 'create':
        return '新增';
      case 'edit':
        return '修改';
      case 'detail':
        return '详情';
      default:
        return '';
    }
  });

  const [registerForm, { setFieldsValue, validate, updateSchema, resetFields }] = useForm({
    schemas: tenantApplicationFormSchemas,
    showActionButtonGroup: false,
  });

  const [registerModal, { closeModal, setModalProps }] = useModalInner((data) => {
    setModalProps({ confirmLoading: false });
    type.value = data.type;
    if (type.value !== 'create') {
      recordId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    } else {
      resetFields();
    }
    updateSchema(
      tenantApplicationFormSchemas.map((item) => {
        return {
          field: item.field,
          componentProps: {
            disabled: type.value === 'detail',
          },
        };
      })
    );
  });

  const handleSubmit = async () => {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      if (type.value === 'create') {
        await createTenantApplication(values);
        message.success('绑定应用成功');
      }
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  const handleCancel = () => {
    closeModal();
  };
</script>
